<?php
namespace App\Admin\Controllers;

use App\Admin\Filters\WorshipBibleChapterFilter;
use App\Admin\Models\SystemModel;
use App\Admin\Models\WorshipBibleChapter;
use App\Admin\Requests\WorshipBibleChapterRequest;
use App\Admin\Resources\WorshipBibleChapterResource;
use Illuminate\Support\Facades\Cache;

class WorshipBibleChapterController extends Controller
{
    public function store(
        WorshipBibleChapterRequest $request, 
        WorshipBibleChapter $worshipBibleChapter
    ){
        $inputs = $request->validated();
        $token = md5(json_encode($inputs));
        unset($inputs['token']);
        if (Cache::get($token) == 2) {
            return $this->error('请不要重复提交数据');
        } 
        Cache::put($token, 1);
        $worshipBibleChapter = $worshipBibleChapter->add($inputs);
        Cache::put($token, 2);

        return $this->created(WorshipBibleChapterResource::make($worshipBibleChapter));
    }

    public function create()
    {
        return $this->ok();
    }

    public function update(
        WorshipBibleChapterRequest $request, 
        WorshipBibleChapter $worshipBibleChapter
    ){
        $inputs = $request->validated();
        $worshipBibleChapter->update($inputs);

        return $this->created(WorshipBibleChapterResource::make($worshipBibleChapter));
    }

    public function edit(WorshipBibleChapter $worshipBibleChapter)
    {
        return $this->ok(WorshipBibleChapterResource::make($worshipBibleChapter));
    }
    
    public function destroy(
        WorshipBibleChapter $worshipBibleChapter
    ){
        $worshipBibleChapter->delete();
        return $this->noContent();
    }

    public function index(
        WorshipBibleChapterFilter $filter,
        WorshipBibleChapter $worshipBibleChapter
    ){
        $worshipBibleChapters = WorshipBibleChapter::withTrashed(isRestore())
            ->filter($filter)
            ->select(SystemModel::getFields($worshipBibleChapter->getTable()))
            ->paginate();

        return $this->ok(WorshipBibleChapterResource::collection($worshipBibleChapters));
    }

    public function show(
        Int $id
    ){
        $worshipBibleChapter = WorshipBibleChapter::withTrashed(isRestore())
            ->select(SystemModel::getFields(app(WorshipBibleChapter::class)->getTable(), 'detail'))
            ->find($id);
        return $this->ok(WorshipBibleChapterResource::make($worshipBibleChapter));
    }
}
